import { Tooltip, Button ,Input,Form, Col, Row, Select, Checkbox, Radio} from 'antd';
import eventBus, { useSubscribe } from "../../../framework/common/eventBus";
import request from "../../../framework/common/utils/request";

import message from "../../../framework/common/utils/message";

//几个审批类型公用的字段
import getInitFormData from './getInitFormData';//获取初始化表单数据
import InitiaterOrg from "../components/InitiaterOrg";//发起组织
import Opinion from "../components/Opinion";//审批意见
import CClist from "../components/CClist";//抄送人
import SignField from "../components/SignField";//签章
import { useEffect, useLayoutEffect, useState } from 'react';

const { Option } = Select;

//驳回表单
export default function({
    tplData,
    urlPrefix,
    formRef,
    approveType="RollBack",
    approveText
}){
    const [form] = Form.useForm();//表单对象
    formRef.current = form;//穿透form对象给父组件

    //表单默认值
    if(!tplData.__approveForm__[approveType]){
        tplData.__approveForm__[approveType] = getInitFormData({
            tplData: tplData,
            fields: {
                opinion: '',//审批意见
                initiater_org_id: '',//审批组织id
                initiater_org_name:'',//审批组织中文名
                step_cc_list: [],//抄送人
                sign_id: tplData.ProfileSign?.default_sign?.id || "", //签章
                radio_back: '0',//打回到
                roll_back_type: null,//驳回方式 0->默认驳回重走，1->默认驳回不重走，-1->用户指定
                step_id: null
            }
        })
    }

    //更新驳回到的步骤
    function updataStep_id(formData){
        let radio_back = 0;
        if(formData){//给了数据，就直接取
            radio_back = formData.radio_back;
        }else{//没给取表单的radio_back字段
            radio_back = form.getFieldValue("radio_back");
        }
        if(tplData.canRejectSteps && tplData.canRejectSteps.length > 0){//存在可打回的步骤时
            let step_id = "";
            if(radio_back == 0){//打回到发起
                step_id = tplData.canRejectSteps[0].step_define_id;
            }else{//打回到上一步或者任意步骤
                step_id = tplData.canRejectSteps[tplData.canRejectSteps.length-1].step_define_id;
            }
            updateFormDataAndTplData({
                step_id: step_id
            });
        }
    }

    //设置发起表单数据，用于ant表单更新后，反向更新tplData内发起表单的数据
    function updateTplData(data){
        tplData.__approveForm__[approveType] = {
            ...tplData.__approveForm__[approveType], 
            ...data
        };
        
        setShowStep_id(tplData.__approveForm__[approveType]['radio_back'] == 2);
    }

    //更新表单值
    function updateFormDataAndTplData(data){
        form.setFieldsValue(data);//更新表单值
        updateTplData(data);//更新tplData值
    }

    //打回步骤显示状态
    const [showStep_id, setShowStep_id] = useState(tplData.__approveForm__[approveType]['radio_back'] == 2);

    //可打回的步骤
    const [canRejectSteps, setCanRejectSteps] = useState(tplData?.canRejectSteps || []);
    
    useEffect(function(){
        if(!canRejectSteps.length){
            request({
                method: "post",
                url: "/flowinstance/approval/can-reject-steps",
                data: { node_id: tplData.NodeInfo.node_id },
                needCancelToken: true,
                noTip: true//请求错误时，axios不展示公共错误
            }).then(function(resObj){
                if (resObj.code == 1 && resObj.data) {
                    if (resObj.data.length) {
                        tplData.canRejectSteps = resObj.data;
                        setCanRejectSteps(tplData.canRejectSteps);//更新可打回步骤列表
                        
                        let roll_back_type = null;
                        //设置打回重走不重走默认值
                        //驳回默认选项，0->默认驳回重走，1->默认驳回不重走，-1->用户指定
                        if(tplData?.ProcessInfo?.RejectReDo == 'all'){//如果存在打回是否重走的默认值配置 并且驳回方式是都勾选的状态下
                            if(tplData?.ProcessInfo?.RejectReDoOption == 0){//默认为重走
                                roll_back_type = "1";
                            }
                            if(tplData?.ProcessInfo?.RejectReDoOption == 1){//默认为不重走
                                roll_back_type = "0";
                            }
                            //都不满足则没有默认值，需要用户手动选择
                        }
                        if(tplData?.ProcessInfo?.RejectReDo === 'skip'){//驳回方式配置的是 驳回不重走 
                            roll_back_type = "0";
                        }
                        if(tplData?.ProcessInfo?.RejectReDo === 'retrace'){//驳回方式配置的是 驳回重走 
                            roll_back_type = "1";
                        }
                        
                        updataStep_id();
                        if(roll_back_type){
                            updateFormDataAndTplData({
                                roll_back_type: roll_back_type,//驳回方式
                            });//更新表单和tplData
                        }

                    } else {
                        message.info({
                            content: "该步骤已被处理,刷新页面查看",
                            afterClose:function(){
                                window.location.href = window.location.href;
                            }
                        });
                    }
                } else {
                    message.info({
                        content: resObj.message,
                        afterClose:function(){
                            window.location.href = window.location.href;
                        }
                    });
                }
            },);
        }
    }, [])

    //console.log(approveType + "初始化表单数据",tplData.__approveForm__[approveType])

    return <Form
                form={form}
                name="basic"
                labelAlign={"left"}
                colon={false}
                labelCol={{
                    flex: "80px",
                }}
                onValuesChange={(value,allValues)=>{
                    
                    if(value.hasOwnProperty("radio_back")){//如果是打回到触发的change
                        updataStep_id(allValues);//更新打回到步骤
                    }
                    //回填表单数据到tplData
                    //比较特殊需要额外回填的，单独到组件内的change事件处理，比如发起组织
                    updateTplData(allValues);
                }}
                initialValues={tplData.__approveForm__[approveType]}
                autoComplete="off"
            >
                <Form.Item
                    label={approveText + "意见"}
                    name="opinion"
                    rules={[
                        {
                            required: true,
                            message: '',
                        }
                    ]}
                >
                    <Opinion  approveType={approveType} placeholder={"请输入" + approveText + "意见"}></Opinion>
                </Form.Item>

                <div className='overflow-hidden'>
                    <Form.Item
                        className="mb-10px float-left w-[330px]"
                        label={approveText + "到"}
                        name="radio_back"
                        rules={[
                            {
                                required: true,
                                message: '',
                            },
                        ]}
                    >
                        <Radio.Group name="radiogroup">
                            <Radio value="0" key="0">发起</Radio>
                            <Radio value="1" key="1">上一步</Radio>
                            <Radio value="2" key="2">任意步骤</Radio>
                        </Radio.Group>
                    </Form.Item>
                    {
                        showStep_id
                        && <Form.Item
                            className="float-right mb-10px w-36"
                            label=""
                            name="step_id"
                            rules={[
                                {
                                    required: true,
                                    message: '',
                                },
                            ]}
                        >
                            <Select 
                                placeholder="请选择步骤"
                                allowClear
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}>
                                {
                                    canRejectSteps.map(function(item){
                                        return <Option key={item.step_define_id} value={item.step_define_id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                    }
                </div>

                {
                    tplData?.ProcessInfo?.RejectReDo === 'all' //驳回方式配置的是 驳回重走 || 驳回不重走 此时手动选择
                    ? <Form.Item
                        className="mb-10px"
                        label={approveText + "方式"}
                        name="roll_back_type"
                        rules={[
                            {
                                required: true,
                                message: '',
                            },
                        ]}
                    >
                        <Radio.Group name="roll_back_type">
                            <Radio value="1">重走</Radio>
                            <Radio value="0">不重走</Radio>
                        </Radio.Group>
                    </Form.Item>
                    : <Form.Item
                        className="mb-10px"
                        label={approveText + "方式"}
                        name="roll_back_type"
                        rules={[
                            {
                                required: true,
                                message: '',
                            },
                        ]}
                    >
                        {
                            tplData?.ProcessInfo?.RejectReDo === 'retrace' //驳回方式配置的是 驳回重走 
                            && <p className='mb-0'>重走</p>
                        }
                        {
                            tplData?.ProcessInfo?.RejectReDo === 'skip' //驳回方式配置的是 驳回不重走 
                            && <p className='mb-0'>不重走</p>
                        }
                    </Form.Item>
                }

                <Form.Item
                    className="mb-10px"
                    label="审批组织"
                    name="initiater_org_id"
                    rules={[
                        {
                            required: true,
                            message: '',
                        },
                    ]}
                >
                    <InitiaterOrg
                        approveType={approveType}
                        form={form}
                        updateTplData={updateTplData}
                    ></InitiaterOrg>
                </Form.Item>
                {
                    tplData.show_step_cc === true
                    && <Form.Item
                            className="mb-10px"
                            label="抄送人"
                            name="step_cc_list"
                        >
                            <CClist
                                tplData={tplData}
                                urlPrefix={urlPrefix}
                                placeholder={"请选择抄送人"}
                            ></CClist>
                        </Form.Item>
                }
                {
                    (tplData.ProfileSign?.enable_sign == 1)
                    && <Form.Item
                        className="mb-0"
                        label="选择签章"
                        name="sign_id"
                        rules={[
                            {
                                required: true,
                                message: '',
                            }
                        ]}
                    >
                        <SignField 
                            tplData={tplData}
                        >
                        </SignField>
                    </Form.Item>
                }
            </Form>
}